package com.example.servlet;
import com.example.dao.StudentMapper;
import com.example.pojo.StuClass;
import com.example.utils.MybatisUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "GetClassesServlet", urlPatterns = "/GetClassesServlet")
public class GetClassesServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 设置响应类型为 JSON
        response.setContentType("application/json");

        // 获取数据库连接会话
        try (SqlSession sqlSession = MybatisUtils.getSqlSession()) {
            // 使用 MyBatis 查询班级列表
            StudentMapper studentDao = sqlSession.getMapper(StudentMapper.class);
            List<String> classes = studentDao.getAllClasses();

            // 将班级列表转换为 JSON 格式
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonClasses = objectMapper.writeValueAsString(classes);

            // 将 JSON 响应发送给客户端
            response.getWriter().write(jsonClasses);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("Error occurred while fetching classes.");
        }
    }
}
